<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分类管理</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap Icons -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.11.0/font/bootstrap-icons.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 2rem 0;
            padding-top: 90px; /* 为导航栏留空间 */
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        /* 导航栏样式 */
        .top-navbar {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1030;
        }

        .top-navbar .navbar-brand {
            font-size: 1.3rem;
            letter-spacing: 0.5px;
            font-weight: 700;
        }

        .top-navbar .nav-link {
            color: rgba(255,255,255,0.85) !important;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            margin: 0 0.2rem;
            transition: all 0.2s;
        }

        .top-navbar .nav-link:hover,
        .top-navbar .nav-link.active {
            background: rgba(255,255,255,0.15);
            color: white !important;
        }

        .main-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            background: white;
        }

        .header-section {
            background: linear-gradient(135deg, #4f46e5, #4338ca);
            color: white;
            padding: 2rem;
            border-radius: 15px 15px 0 0;
            margin: -1.5rem -1.5rem 1.5rem -1.5rem;
        }

        .category-card {
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s;
            background: white;
        }

        .category-card:hover {
            border-color: #4f46e5;
            box-shadow: 0 5px 15px rgba(79, 70, 229, 0.2);
            transform: translateY(-2px);
        }

        .category-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .category-name {
            font-size: 1.3rem;
            font-weight: 700;
            color: #1f2937;
        }

        .category-code {
            background: #f3f4f6;
            padding: 0.3rem 0.8rem;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            color: #6b7280;
        }

        .category-stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
            margin: 1rem 0;
        }

        .stat-item {
            text-align: center;
            padding: 0.8rem;
            background: #f9fafb;
            border-radius: 8px;
        }

        .stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #4f46e5;
        }

        .stat-label {
            font-size: 0.875rem;
            color: #6b7280;
        }

        .badge-status {
            padding: 0.4rem 1rem;
            border-radius: 20px;
            font-weight: 600;
        }

        .btn-action {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            margin: 0 0.2rem;
        }

        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #6b7280;
        }

        .empty-state i {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.3;
        }
    </style>
</head>
<body>

<script>
    // 自动高亮当前页面的导航项
    document.addEventListener('DOMContentLoaded', function() {
        const currentPath = window.location.pathname;
        const navLinks = document.querySelectorAll('.top-navbar .nav-link');

        // 移除所有active类
        navLinks.forEach(link => link.classList.remove('active'));

        // 根据当前路径添加active类
        navLinks.forEach(link => {
            const href = link.getAttribute('href');
            if (currentPath === href ||
                (href !== '/dashboard' && currentPath.startsWith(href))) {
                link.classList.add('active');
            }
        });
    });
</script>

<!-- 顶部导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark top-navbar">
    <div class="container-fluid">
        <a class="navbar-brand fw-bold" href="/dashboard">
            <i class="bi bi-box-seam-fill me-2"></i>商品管理系统
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/dashboard">
                        <i class="bi bi-speedometer2"></i> Dashboard
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/product/list">
                        <i class="bi bi-box"></i> 商品管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/category/list">
                        <i class="bi bi-tags"></i> 分类管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/log/list">
                        <i class="bi bi-clock-history"></i> 操作日志
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/doc">
                        <i class="bi bi-book"></i> API文档
                    </a>
                </li>
            </ul>
            <div class="d-flex align-items-center">
                <!-- 用户信息 -->
                <div th:if="${currentUser}" class="me-3 text-white">
                    <small>欢迎,</small>
                    <strong th:text="${currentUser.realName ?: currentUser.username}"></strong>
                </div>
                
                <a href="/product/add" class="btn btn-light btn-sm me-2">
                    <i class="bi bi-plus-circle"></i> 新增商品
                </a>
                <a href="/druid" target="_blank" class="btn btn-outline-light btn-sm me-2">
                    <i class="bi bi-speedometer"></i> 监控
                </a>
                <!-- 登出按钮 -->
                <a href="/auth/logout" class="btn btn-outline-light btn-sm">
                    <i class="bi bi-box-arrow-right"></i> 登出
                </a>
            </div>
        </div>
    </div>
</nav>

<div class="container main-container">
    <div class="card">
        <div class="card-body p-4">
            <!-- 页面标题 -->
            <div class="header-section">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h2 class="mb-2"><i class="bi bi-tags"></i> 分类管理</h2>
                        <p class="mb-0 opacity-75">管理商品分类和层级结构</p>
                    </div>
                    <div>
                        <button class="btn btn-light btn-lg" data-bs-toggle="modal" data-bs-target="#categoryModal" onclick="openAddModal()">
                            <i class="bi bi-plus-circle"></i> 新增分类
                        </button>
                        <a href="/product/list" class="btn btn-outline-light btn-lg">
                            <i class="bi bi-box-seam"></i> 商品管理
                        </a>
                    </div>
                </div>
            </div>

            <!-- 分类列表 -->
            <div th:if="${#lists.isEmpty(categories)}" class="empty-state">
                <i class="bi bi-inbox"></i>
                <h5>暂无分类</h5>
                <p>点击"新增分类"按钮创建第一个分类</p>
            </div>

            <div class="row" th:if="${!#lists.isEmpty(categories)}">
                <div class="col-md-6" th:each="category : ${categories}">
                    <div class="category-card">
                        <div class="category-header">
                            <div>
                                <div class="category-name" th:text="${category.categoryName}"></div>
                                <code class="category-code" th:text="${category.categoryCode}"></code>
                            </div>
                            <div>
                                <span th:if="${category.isActive == 1}" class="badge bg-success badge-status">启用</span>
                                <span th:if="${category.isActive == 0}" class="badge bg-secondary badge-status">禁用</span>
                            </div>
                        </div>

                        <p class="text-muted mb-3" th:text="${category.description ?: '暂无描述'}"></p>

                        <div class="category-stats">
                            <div class="stat-item">
                                <div class="stat-value" th:text="${category.productCount ?: 0}"></div>
                                <div class="stat-label">商品数量</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value" th:text="${category.sortOrder ?: 0}"></div>
                                <div class="stat-label">排序</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value">
                                    <i class="bi bi-check-circle text-success" th:if="${category.isActive == 1}"></i>
                                    <i class="bi bi-x-circle text-secondary" th:if="${category.isActive == 0}"></i>
                                </div>
                                <div class="stat-label">状态</div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end mt-3">
                            <button class="btn btn-primary btn-sm btn-action edit-btn"
                                    th:data-id="${category.id}"
                                    data-bs-toggle="modal" data-bs-target="#categoryModal">
                                <i class="bi bi-pencil"></i> 编辑
                            </button>
                            <button class="btn btn-danger btn-sm btn-action delete-btn"
                                    th:data-id="${category.id}"
                                    th:data-name="${category.categoryName}"
                                    th:data-count="${category.productCount}">
                                <i class="bi bi-trash"></i> 删除
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新增/编辑分类模态框 -->
<div class="modal fade" id="categoryModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="modalTitle">新增分类</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="categoryForm">
                    <input type="hidden" id="categoryId">

                    <div class="mb-3">
                        <label for="categoryName" class="form-label">分类名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="categoryName" required>
                        <div class="form-text">例如：电子产品、服装鞋帽</div>
                    </div>

                    <div class="mb-3">
                        <label for="categoryCode" class="form-label">分类编码 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="categoryCode"
                               pattern="[A-Z0-9_]+" required>
                        <div class="form-text">仅支持大写字母、数字和下划线，例如：ELECTRONICS</div>
                    </div>

                    <div class="mb-3">
                        <label for="description" class="form-label">分类描述</label>
                        <textarea class="form-control" id="description" rows="3"></textarea>
                    </div>

                    <div class="mb-3">
                        <label for="sortOrder" class="form-label">排序顺序</label>
                        <input type="number" class="form-control" id="sortOrder" value="0" min="0">
                        <div class="form-text">数字越小越靠前</div>
                    </div>

                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="isActive" checked>
                            <label class="form-check-label" for="isActive">启用此分类</label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveCategory()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="bi bi-exclamation-triangle"></i> 确认删除</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="deleteMessage"></p>
                <div class="alert alert-warning" id="deleteWarning" style="display: none;">
                    <i class="bi bi-exclamation-circle"></i>
                    <strong>警告：</strong>该分类下有商品，删除前请先处理这些商品！
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn" onclick="confirmDelete()">确认删除</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
    let currentCategoryId = null;
    const categoryModal = new bootstrap.Modal(document.getElementById('categoryModal'));
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

    // 打开新增模态框
    function openAddModal() {
        document.getElementById('modalTitle').textContent = '新增分类';
        document.getElementById('categoryForm').reset();
        document.getElementById('categoryId').value = '';
        document.getElementById('isActive').checked = true;
    }

    // 使用事件委托处理编辑按钮
    document.addEventListener('click', function(e) {
        if (e.target.closest('.edit-btn')) {
            const btn = e.target.closest('.edit-btn');
            const id = btn.getAttribute('data-id');
            editCategory(id);
        }

        if (e.target.closest('.delete-btn')) {
            const btn = e.target.closest('.delete-btn');
            const id = btn.getAttribute('data-id');
            const name = btn.getAttribute('data-name');
            const count = parseInt(btn.getAttribute('data-count') || 0);
            deleteCategory(id, name, count);
        }
    });

    // 编辑分类
    function editCategory(id) {
        document.getElementById('modalTitle').textContent = '编辑分类';

        // 获取分类详情
        $.ajax({
            url: `/category/get/${id}`,
            type: 'GET',
            success: function(result) {
                if (result.success) {
                    const category = result.data;
                    document.getElementById('categoryId').value = category.id;
                    document.getElementById('categoryName').value = category.categoryName;
                    document.getElementById('categoryCode').value = category.categoryCode;
                    document.getElementById('description').value = category.description || '';
                    document.getElementById('sortOrder').value = category.sortOrder || 0;
                    document.getElementById('isActive').checked = category.isActive === 1;
                } else {
                    alert('获取分类信息失败：' + result.message);
                }
            }
        });
    }

    // 保存分类
    function saveCategory() {
        const id = document.getElementById('categoryId').value;
        const formData = {
            id: id || null,
            categoryName: document.getElementById('categoryName').value,
            categoryCode: document.getElementById('categoryCode').value.toUpperCase(),
            description: document.getElementById('description').value,
            sortOrder: parseInt(document.getElementById('sortOrder').value) || 0,
            isActive: document.getElementById('isActive').checked ? 1 : 0
        };

        // 表单验证
        if (!formData.categoryName || !formData.categoryCode) {
            alert('请填写必填项！');
            return;
        }

        const url = id ? '/category/update' : '/category/add';
        const method = id ? 'PUT' : 'POST';

        $.ajax({
            url: url,
            type: method,
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(result) {
                if (result.success) {
                    alert(id ? '更新成功！' : '新增成功！');
                    categoryModal.hide();
                    location.reload();
                } else {
                    alert('操作失败：' + result.message);
                }
            },
            error: function() {
                alert('操作失败，请检查网络连接！');
            }
        });
    }

    // 删除分类
    function deleteCategory(id, name, productCount) {
        currentCategoryId = id;

        document.getElementById('deleteMessage').textContent =
            `确定要删除分类"${name}"吗？`;

        if (productCount > 0) {
            document.getElementById('deleteWarning').style.display = 'block';
            document.getElementById('confirmDeleteBtn').disabled = true;
        } else {
            document.getElementById('deleteWarning').style.display = 'none';
            document.getElementById('confirmDeleteBtn').disabled = false;
        }

        deleteModal.show();
    }

    // 确认删除
    function confirmDelete() {
        if (currentCategoryId) {
            $.ajax({
                url: `/category/delete/${currentCategoryId}`,
                type: 'DELETE',
                success: function(result) {
                    if (result.success) {
                        alert('删除成功！');
                        deleteModal.hide();
                        location.reload();
                    } else {
                        alert('删除失败：' + result.message);
                    }
                },
                error: function() {
                    alert('删除失败，请稍后重试！');
                }
            });
        }
    }

    // 将商品编码转为大写
    document.getElementById('categoryCode').addEventListener('input', function() {
        this.value = this.value.toUpperCase();
    });
</script>
</body>
</html>